﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using Maticsoft.DBUtility;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace Logistics.Server.Service
{
    /// <summary>
    /// Summary description for DataService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    public class DataService : System.Web.Services.WebService, IDateService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }

        /// <summary>
        /// 获取用户状态
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="psd"></param>
        /// <returns>0：停用，-1：不存在；1：可用</returns>
        [WebMethod]
        public int GetUserState(string userName, string psd)
        {
            DataSet ds = new DataSet();
            ds = DbSQL.Query("select DelUser from Users where  UserName='" + userName + "' and UserPwd='" + psd + "'");
            if (ds == null || ds.Tables[0].Rows.Count == 0)
                return -1;//用户不存在
            else
            {
                string delState = ds.Tables[0].Rows[0][0].ToString();
                if (String.IsNullOrEmpty(delState))
                {
                    return 1;
                }
                else
                    return 0;//已停用的用户
            }
        }

        /// <summary>
        /// 申请注册（C/S专用）
        /// </summary>
        /// >MAC地址
        /// 硬盘型号
        /// CPU型号
        /// IP
        /// 主机名
        /// 创建人
        ///备注
        /// <returns>成功：1；失败：0</returns>
        [WebMethod]
        public string ApplicationRegedit(List<string> list)
        {
            string mac = list[0];
            string hdId = list[1];
            string cpu = list[2];
            string ip = list[3];
            string hostUser = list[4];
            string createUser = list[5];
            string remark = list[6];
            string colums = "(CPU,PhysicalMemory,Keyboard,PointingDevice,FloppyDrive,DiskDrive,CDROMDrive,BaseBoard,Modem,ModemPort,"
                        + "HD,BIOS,ParallelPort,SerialPort,SerialPortConfig,SoundDevice,SystemSlot,USBController,Network,NetworkConfig,"
                        + "Printer,PrinterConfig,PrintJob,DesktopMonitor,Display,DisplayConfig,MAC,TCPIPPrinterPort,VideoController,VideoSettings,"
                        + "Count,IsUsed,CheckCode,Createdtm,CreateUser,Edit,EditUser,Auditdtm,AuditUser,Auditing,"
                        + "State,attr1,attr2,attr3,attr4,attr5,attr6)";
            StringBuilder sbd = new StringBuilder();
            sbd.Append("('" + cpu + "',");
            sbd.Append("'',");
            sbd.Append("'',");
            sbd.Append("'',");
            sbd.Append("'',");
            sbd.Append("'',");
            sbd.Append("'',");
            sbd.Append("'',");
            sbd.Append("'',");
            sbd.Append("'',");
            sbd.Append("'" + hdId + "',");//11
            sbd.Append("'',");
            sbd.Append("'',");
            sbd.Append("'',");
            sbd.Append("'',");
            sbd.Append("'',");
            sbd.Append("'',");
            sbd.Append("'',");
            sbd.Append("'',");
            sbd.Append("'',");
            sbd.Append("'',");
            sbd.Append("'',");
            sbd.Append("'',");
            sbd.Append("'',");
            sbd.Append("'',");
            sbd.Append("'',");
            sbd.Append("'" + mac + "',");//16
            sbd.Append("'',");
            sbd.Append("'',");
            sbd.Append("'',");
            sbd.Append("0,");
            sbd.Append("0,");
            sbd.Append("'',");
            sbd.Append("'" + DateTime.Now.ToString() + "',");
            sbd.Append("'" + createUser + "',");
            sbd.Append("'',");
            sbd.Append("'',");
            sbd.Append("'',");
            sbd.Append("'',");
            sbd.Append("0,");
            sbd.Append("0,");
            sbd.Append("'" + ip + "',");
            sbd.Append("'" + hostUser + "',");
            sbd.Append("'',");
            sbd.Append("'" + remark + "',");
            sbd.Append("1,");
            sbd.Append("0)");
            string insertSQL = "insert into UsersMachineRegister" + colums + " values" + sbd.ToString();
            try
            {
                return DbSQL.ExecuteSql(insertSQL).ToString();
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }
        /// <summary>
        /// 客户端上传运单信息
        /// </summary>
        /// <param name="columns">列名</param>
        /// <param name="list">数据集</param>
        /// <param name="index">主键位置</param>
        /// <returns></returns>
        [WebMethod(Description = "客户端上传运单信息")]
        public int AddListData(string columns, List<string> list, int index)
        {

            string str = string.Empty;
            if (list.Count > 0)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    string str2 = this.JudeConsignor(list[i]);
                    string str3 = this.JudeConsignee(list[i]);
                    string[] strArray = list[i].Split(new char[] { ',' });
                    if (str2 != "0")
                    {
                        strArray[13] = str2;
                    }
                    if (str3 != "0")
                    {
                        strArray[5] = str3;
                    }
                    string str4 = list[i];
                    str = str + "|" + str4;
                }
            }
            SqlParameter[] parameters = new SqlParameter[] { new SqlParameter("@Columns", SqlDbType.NVarChar), new SqlParameter("@SplitString", SqlDbType.NText), new SqlParameter("@index", SqlDbType.Int) };
            parameters[0].Value = columns;
            parameters[1].Value = str.Substring(1);
            parameters[2].Value = index;
            int rowsAffected = -1;
            return DbSQL.RunProcedure("up_ClientUpload", parameters, out rowsAffected);


        }

        /// <summary>
        /// DbSQL.ExecuteSql(sql)
        /// </summary>
        /// <param name="sql">string</param>
        /// <returns>int</returns>
        [WebMethod(Description = "执行SQL,返回记录数")]
        public int ExecuteCountSql(string sql)
        {
            return DbSQL.ExecuteCountSql(sql);
        }

        [WebMethod(Description = "上传日志-新修改")]
        public int UpLoadLogs(string table, string columns, List<string> lstValues)
        {
            try
            {
                int i = 0;
                if (lstValues.Count > 0)
                {
                    foreach (string str in lstValues)
                    {
                        string values = string.Empty;
                        if (str.StartsWith(","))
                        {
                            values = str.Substring(1, str.Length - 1);
                        }
                        StringBuilder strSql = new StringBuilder();
                        strSql.Append("insert into " + table + "(");
                        strSql.Append(columns);
                        strSql.Append(")values(");

                        strSql.Append(values + ")");
                        i += DbSQL.ExecuteSql(strSql.ToString());
                    }
                }

                return i;
            }
            catch (Exception)
            {
                return 0;
            }
        }

        [WebMethod(Description = "获取服务器数据集")]
        public DataSet GetSynchronous(string where, string FieldSet, string tabTable)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("SELECT " + FieldSet + " FROM [" + tabTable + "] ");
            if (!string.IsNullOrEmpty(where))
            {
                sb.Append(" where ");
                sb.Append(where);
            }
            return DbSQL.Query(sb.ToString());
        }



        /// <summary>
        /// 收货客户信息维护
        /// </summary>
        /// <param name="strs"></param>
        /// <returns></returns>
        public string JudeConsignee(string strs)
        {
            string[] strArray = strs.Split(new char[] { ',' });
            string str2 = "";//客户名称
            string str3 = "";//客户电话
            string str4 = "";//客户手机
            string str5 = "";//客户地址
            string str6 = "";//客户所属公司
            string str7 = "";//客户所属站点

            str2 = strArray[11].ToString();//客户名称

            str3 = strArray[7].ToString();//客户电话

            str4 = strArray[8].ToString();//客户手机

            str5 = strArray[10].ToString();//客户地址

            str6 = strArray[9].ToString();//客户所属公司

            str7 = strArray[3].ToString();//客户所属站点   

            bool flag = IsCustomExit(true, str2, str3, str4, "", str7);
            if (!flag)
            {
                string str = this.getNumStr("Custom");
                StringBuilder builder = new StringBuilder();
                builder.Append("INSERT INTO [Custom] ([CustomID],[CustomType],[CustomName],[IdentityNum],[Tel],[Mobil],[NetworkID],[BankNum],[CompanyName] ,[CompanyAddress],[IsAutoCreate],[Edit],[Createdtm] ,[CreateUser],[GoodsID])values(");
                builder.Append("'" + str + "',");//客户编号
                builder.Append("'收货客户',");//客户类型
                builder.Append(str2 + ",");//客户名称
                builder.Append("' ',");
                builder.Append(str3 + ",");//客户电话
                builder.Append(str4 + ",");//客户手机
                builder.Append(str7 + ",");//客户所属站点
                builder.Append("' ',");
                builder.Append(str6 + ",");//客户所属公司
                builder.Append(str5 + ",");//客户地址
                builder.Append("'true',");//客户编类型
                builder.Append("'" + DateTime.Now.ToString() + "',");//修改日期
                builder.Append("'" + DateTime.Now.ToString() + "',");//创建日期
                builder.Append("' ',");
                builder.Append("' ')");
                DbSQL.ExecuteSql(builder.ToString());
                return str;
            }
            else
            {
                return "0";
            }

            /* 判断客户是否存在（已废除）
            if (DbSQL.Query("select * from Custom where  (DelSign='0' or DelSign is null) and Tel=" + str3 + " and Mobil=" + str4 + " and CustomName=" + str2 + " and NetworkID=" + str7).Tables[0].Rows.Count < 1)
            {
                if (!string.IsNullOrEmpty(str2))
                {
                    string str = this.getNumStr("Custom");
                    StringBuilder builder = new StringBuilder();
                    builder.Append("INSERT INTO [Custom] ([CustomID],[CustomType],[CustomName],[IdentityNum],[Tel],[Mobil],[NetworkID],[BankNum],[CompanyName] ,[CompanyAddress],[IsAutoCreate],[Edit],[Createdtm] ,[CreateUser],[GoodsID])values(");
                    builder.Append("'" + str + "',");//客户编号
                    builder.Append("'收货客户',");//客户类型
                    builder.Append(str2 + ",");//客户名称
                    builder.Append("' ',");
                    builder.Append(str3 + ",");//客户电话
                    builder.Append(str4 + ",");//客户手机
                    builder.Append(str7 + ",");//客户所属站点
                    builder.Append("' ',");
                    builder.Append(str6 + ",");//客户所属公司
                    builder.Append(str5 + ",");//客户地址
                    builder.Append("'true',");//客户编类型
                    builder.Append("'" + DateTime.Now.ToString() + "',");//修改日期
                    builder.Append("'" + DateTime.Now.ToString() + "',");//创建日期
                    builder.Append("' ',");
                    builder.Append("' ')");
                    DbSQL.ExecuteSql(builder.ToString());
                    return str;
                }
                return "0";
            }
            return "0";
             */
        }

        public string JudeConsignor(string strs)
        {
            string[] strArray = strs.Split(new char[] { ',' });
            string str2 = "";
            string str3 = "";
            string str4 = "";
            string str5 = "";
            string str6 = "";
            string str7 = "";
            string str8 = "";

            str2 = strArray[14].ToString();//客户姓名

            str3 = strArray[15].ToString();//客户电话

            str4 = strArray[16].ToString();//客户手机

            str5 = strArray[18].ToString();//客户地址

            str6 = strArray[17].ToString();//公司名

            str7 = strArray[20].ToString();//银行卡号

            str8 = strArray[1].ToString();//发货客户所属站点（源站点）

            bool flag = IsCustomExit(false, str2, str3, str4, str7, str8);
            if (!flag)
            {
                string str = this.getNumStr("Custom");
                StringBuilder builder = new StringBuilder();
                builder.Append("INSERT INTO [Custom] ([CustomID],[CustomType],[CustomName],[IdentityNum],[Tel],[Mobil],[NetworkID],[BankNum],[CompanyName],[CompanyAddress],[IsAutoCreate],[Createdtm],[Edit],[GoodsID],[CreateUser])values(");
                builder.Append("'" + str + "',");//客户编号
                builder.Append("'发货客户',");
                builder.Append(str2 + ",");//客户姓名
                builder.Append("' ',");//
                builder.Append(str3 + ",");//电话
                builder.Append(str4 + ",");//手机号
                builder.Append(str8 + ",");//所属站点
                builder.Append(str7 + ",");//银行卡号
                builder.Append(str6 + ",");//公司名
                builder.Append(str5 + ",");//地址
                builder.Append("'true',");
                builder.Append("'" + DateTime.Now.ToString() + "',");
                builder.Append("'" + DateTime.Now.ToString() + "',");
                builder.Append("' ',");
                builder.Append("' ')");
                DbSQL.ExecuteSql(builder.ToString());
                return str;
            }
            else
            {
                return "0";
            }

            //if (DbSQL.Query("select * from Custom where (DelSign='0' or DelSign is null) and Tel =" + str3 + " and Mobil=" + str4 + "  and CustomName=" + str2 + " and BankNum=" + str7 + " and NetworkID=" + str8).Tables[0].Rows.Count < 1)
            //{
            //    if (!string.IsNullOrEmpty(str2))
            //    {
            //        string str = this.getNumStr("Custom");
            //        StringBuilder builder = new StringBuilder();
            //        builder.Append("INSERT INTO [Custom] ([CustomID],[CustomType],[CustomName],[IdentityNum],[Tel],[Mobil],[NetworkID],[BankNum],[CompanyName],[CompanyAddress],[IsAutoCreate],[Createdtm],[Edit],[GoodsID],[CreateUser])values(");
            //        builder.Append("'" + str + "',");//客户编号
            //        builder.Append("'发货客户',");
            //        builder.Append(str2 + ",");//客户姓名
            //        builder.Append("' ',");//
            //        builder.Append(str3 + ",");//电话
            //        builder.Append(str4 + ",");//手机号
            //        builder.Append(str8 + ",");//所属站点
            //        builder.Append(str7 + ",");//银行卡号
            //        builder.Append(str6 + ",");//公司名
            //        builder.Append(str5 + ",");//地址
            //        builder.Append("'true',");
            //        builder.Append("'" + DateTime.Now.ToString() + "',");
            //        builder.Append("'" + DateTime.Now.ToString() + "',");
            //        builder.Append("' ',");
            //        builder.Append("' ')");
            //        DbSQL.ExecuteSql(builder.ToString());
            //        return str;
            //    }
            //    return "0";
            //}
            //return "0";
        }
        /// <summary>
        /// 获取编号（年+月+日+maxID）
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <returns></returns>
        public string getNumStr(string tableName)
        {
            int maxID = DbSQL.GetMaxID("ID", tableName);
            int year = DateTime.Now.Year;
            int month = DateTime.Now.Month;
            int day = DateTime.Now.Day;
            Random random = new Random();
            int num5 = maxID + 1;
            return (year.ToString() + month.ToString() + day.ToString() + num5.ToString());

        }
        /// <summary>
        /// 判断客户是否存在
        /// </summary>
        /// <param name="sta">true:收货客户;false:发货客户</param>
        /// <param name="customName">客户名</param>
        /// <param name="customTel">电话</param>
        /// <param name="customMobile">手机</param>
        /// <param name="bankNum">银行卡号</param>
        /// <param name="customSiteId">所属站点</param>
        /// <returns></returns>
        private bool IsCustomExit(bool sta, string customName, string customTel, string customMobile, string bankNum, string customSiteId)
        {
            bool flag = false;//不存在
            StringBuilder searchSql1 = new StringBuilder();
            searchSql1.Append(" select count(*) from Custom where (DelSign='0' or DelSign is null) ");
            if (customName.Contains("'"))
            {
                customName = customName.Replace("'", "");
            }
            if (customTel.Contains("'"))
            {
                customTel = customTel.Replace("'", "");
            }
            if (customMobile.Contains("'"))
            {
                customMobile = customMobile.Replace("'", "");
            }
            if (bankNum.Contains("'"))
            {
                bankNum = bankNum.Replace("'", "");
            }
            if (customSiteId.Contains("'"))
            {
                customSiteId = customSiteId.Replace("'", "");
            }
            if (sta)//收货客户
            {
                //1.1:姓名、电话（或手机）同时不为空才能添加此信息
                if (!String.IsNullOrEmpty(customName) && (!String.IsNullOrEmpty(customTel) || !String.IsNullOrEmpty(customMobile)))
                {
                    //1.2 增加其他判断条件
                    searchSql1.Append(" and CustomType='收货客户'");//客户类型
                    searchSql1.Append(" and NetworkID='" + customSiteId.Trim() + "'");//所属站点
                    searchSql1.Append(" and CustomName='" + customName + "'");//客户姓名
                    if (!String.IsNullOrEmpty(customTel))
                    {
                        searchSql1.Append(" and Tel='" + customTel + "'");//座机
                    }
                    if (!String.IsNullOrEmpty(customMobile))
                    {
                        searchSql1.Append(" and Mobil='" + customMobile + "'");//手机
                    }
                    flag = DbSQL.Exists(searchSql1.ToString());
                }
                else
                {
                    flag = true;
                }
            }
            else//发货客户
            {
                //1.1:姓名、电话（或手机）同时不为空才能添加此信息
                if (!String.IsNullOrEmpty(customName) && (!String.IsNullOrEmpty(customTel) || !String.IsNullOrEmpty(customMobile)))
                {
                    //1.2 增加其他判断条件
                    searchSql1.Append(" and CustomType='发货客户'");//客户类型
                    searchSql1.Append(" and NetworkID='" + customSiteId.Trim() + "'");//所属站点
                    searchSql1.Append(" and CustomName='" + customName + "'");//客户姓名
                    if (!String.IsNullOrEmpty(customTel))
                    {
                        searchSql1.Append(" and Tel='" + customTel + "'");//座机
                    }
                    if (!String.IsNullOrEmpty(customMobile))
                    {
                        searchSql1.Append(" and Mobil='" + customMobile + "'");//客手机
                    }
                    if (!String.IsNullOrEmpty(bankNum))
                    {
                        searchSql1.Append(" and BankNum='" + bankNum + "'");//卡号
                    }
                    flag = DbSQL.Exists(searchSql1.ToString());
                }
                else
                {
                    flag = true;
                }
            }

            return flag;
        }


        
    }
}
